<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>案例-头像上传</title>
    <link rel="stylesheet" href="./lib/bootstrap-v4.6.0.css" />
    <style>
      .thumb-box {
        text-align: center;
        margin-top: 50px;
      }

      .thumb {
        width: 250px;
        height: 250px;
        object-fit: cover;
        border-radius: 50%;
      }
    </style>
  </head>

  <body>
    <div class="thumb-box">
      <!-- 头像 -->
      <img src="./images/cover.jpg" class="img-thumbnail thumb" alt="" />
      <div class="mt-2">
        <!-- 文件选择框 -->
        <!-- accept 属性表示可选择的文件类型 -->
        <!-- image/* 表示只允许选择图片类型的文件 -->
        <input
          type="file"
          id="iptFile"
          accept="image/*"
          style="display: none"
        />
        <!-- 选择头像图片的按钮 -->
        <button class="btn btn-primary" id="btnChoose">选择 & 上传图片</button>
      </div>
    </div>

    <script src="../lib/jquery-v3.6.0.js"></script>
    <script src="../案例2 - 头像上传/lib/axios.js"></script>

    <script>
      // 在这之前先设置根地址
      
     
      axios.defaults.baseURL = "http://www.liulongbin.top:3006";
      axios.interceptors.response.use((response) => response.data);
      // 第一步点击button触发input的事件，相当于点了input
      $('#btnChoose').on('click', function () {
        $('#iptFile').trigger('click');
      });
      $('#iptFile').on('change', function (event) {
        let files = event.target.files; //问老师为什么要这么写
        if (!files.length) return;
        let fd = new FormData();
        fd.append('avatar', files[0]);
        uploadAvatar(fd);
      });
      function uploadAvatar(fd) {
        axios.post('/api/upload/avatar', fd).then(result => {
          if (result.status === 200) {
            $('.thumb').attr('src', axios.defaults.baseURL + result.url);
          } else {
            alert(result.msg);
          }
        });
      }
    </script>
  </body>
</html>
